#include "generaldelegate.h"
#include <QDateTime>
#include <QDebug>
#include <QMouseEvent>
GeneralDelegate::GeneralDelegate(QObject *parent) : QStyledItemDelegate(parent)
{
}

void GeneralDelegate::initStyleOption(QStyleOptionViewItem *option, const QModelIndex &index) const
{
    QStyledItemDelegate::initStyleOption(option, index);

    QVariant data = index.model()->data(index, Qt::EditRole);
    if (data.type() == QVariant::DateTime)
    {
        QDateTime dateTime = data.toDateTime();
        option->displayAlignment = Qt::AlignCenter;
        option->text = dateTime.toString("yyyy-MM-dd hh:mm:ss");
    }
    else if (data.type() == QVariant::Int)
    {
        option->displayAlignment = Qt::AlignRight;
        option->text = QString::number(data.toInt());
    }
    else
    {
        option->displayAlignment = Qt::AlignLeft;
        option->text = data.toString();
    }
}

void GeneralDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
    int currentColumn = index.column();
    int columnCount = index.model()->columnCount();
    // 判断是否为最后一列
    bool isLastColumn = (currentColumn == columnCount - 1);
    if (isLastColumn)
    {
        QRect buttonRect = option.rect.adjusted(2, 2, -2, -2); // 调整按钮位置和大小
        QStyleOptionButton buttonOption;
        buttonOption.rect = buttonRect;
        buttonOption.state |= QStyle::State_Enabled;
        buttonOption.state |= QStyle::State_MouseOver;
        buttonOption.palette.setBrush(QPalette::Button, QColor(Qt::red));
        buttonOption.text = "删除";

        painter->save();
        painter->setClipRect(buttonRect);
        QApplication::style()->drawControl(QStyle::CE_PushButton, &buttonOption, painter);
        painter->restore();
    }
    else
    {
        QStyleOptionViewItem options = option;
        initStyleOption(&options, index);
        options.displayAlignment = Qt::AlignCenter; // 居中
        QApplication::style()->drawControl(QStyle::CE_ItemViewItem, &options, painter);
    }
}

bool GeneralDelegate::editorEvent(QEvent *event, QAbstractItemModel *model, const QStyleOptionViewItem &option, const QModelIndex &index)
{
    int currentColumn = index.column();
    int columnCount = index.model()->columnCount();
    // 判断是否为最后一列
    bool isLastColumn = (currentColumn == columnCount - 1);
    if (event->type() == QEvent::MouseButtonRelease && isLastColumn)
    {
        QMouseEvent *mouseEvent = static_cast<QMouseEvent *>(event);
        QRect buttonRect = option.rect.adjusted(2, 2, -2, -2);
        if (buttonRect.contains(mouseEvent->pos()))
        {
            // 触发删除操作
            emit deleteRequested(index);
            return true;
        }
    }
    return QStyledItemDelegate::editorEvent(event, model, option, index);
}
